package org.example.threadobjectclasscommonmethods;

/**
 * @description: 两个线程交替打印1-100的奇偶数用wait和notify
 * @author: MoodAir
 * @Date: 2020/5/10 0010 22:27
 */
public class WaitNotifyPrintOddEvenWait {


  /**
   * 创建静态锁
   */
  private static final Object LOCK = new Object();
  /**
   * 统计字段
   */
  private static int count = 0;

  /**
   * @Author: MoodAir
   * @Description: main方法创建两个线程启动，循环打印单双
   * @Date: 2020/5/10 0010 22:30
   * @param: args
   * @return: void
   * @Version: 1.0
   */
  public static void main(String[] args) {
    new Thread(new TurningRunner(), "奇数").start();
    try {
      Thread.sleep(100);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    new Thread(new TurningRunner(), "偶数").start();
  }


  static class TurningRunner implements Runnable {

    @Override
    public synchronized void run() {
      while (count < 100) {
        /*
          1.拿到锁
          2.打印完，唤醒其他线程，自己就休眠
        */
        synchronized (LOCK) {
          count++;
          System.out.println(Thread.currentThread().getName() + ":" + count);
          LOCK.notify();
          if (count < 100) {
            try {
              LOCK.wait();
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }
        }
      }
    }
  }
}